using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using System.Diagnostics;

namespace RaycasterXPipeline
{
	[ContentProcessor(DisplayName = "Map Processor")]
	public class MapProcessor : ContentProcessor<string, MapContent>
	{
		public override MapContent Process(string input, ContentProcessorContext context)
		{
			MapContent content = new MapContent();

			//split the text by the end-line character
			string[] lines = input.Split('\n');

			//remove all the \r characters and trim the lines
			for (int i = 0; i < lines.Length; i++)
				lines[i] = lines[i].Replace('\r', ' ').Trim();

			//first up is the textures used
			int line = 0;
			do
			{
				//load the texture from the file
				ExternalReference<TextureContent> tex =
					context.BuildAsset<TextureContent, TextureContent>(
						new ExternalReference<TextureContent>(
							Path.Combine(Directory.GetCurrentDirectory(), "Textures\\" + lines[line])),
						"TextureProcessor");

				//add it to our map content
				content.Textures.Add(tex);

				//move to the next line
				line++;
			} while (!string.IsNullOrEmpty(lines[line])); //we're done when we hit an empty line

			//skip over the empty line
			line++;

			//read in the background file
			content.Background = context.BuildAsset<TextureContent, TextureContent>(
				new ExternalReference<TextureContent>(
					Path.Combine(Directory.GetCurrentDirectory(), "Backgrounds\\" + lines[line])),
				"TextureProcessor");

			//skip over the blank line and get right to the layout
			line += 2;

			do
			{
				//read in all the cells in the line
				string[] cells = lines[line].Split(' ');

				//parse all those cells into integer indexes
				int[] cellIndexes = new int[cells.Length];
				for (int i = 0; i < cellIndexes.Length; i++)
					cellIndexes[i] = int.Parse(cells[i]);

				//add the row to the map content
				content.Rows.Add(cellIndexes);

				//move to the next line
				line++;
			} while (line < lines.Length && !string.IsNullOrEmpty(lines[line])); //keep going until we're out of lines

			//return the map content to the writer
			return content;
		}
	}
}